package com.mewp.permissions.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mewp.permissions.model.po.SysRole;
import com.mewp.permissions.model.po.SysUserRole;
import com.mewp.permissions.model.vo.AssginRoleVO;
import com.mewp.permissions.model.vo.SysRoleQueryVo;
import com.mewp.permissions.system.mapper.SysRoleMapper;
import com.mewp.permissions.system.mapper.SysUserRoleMapper;
import com.mewp.permissions.system.service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mewp
 * @version 1.0
 * @date 2023/7/28 01:56
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Override
    public Page<SysRole> selectPage(Integer page, Integer size, SysRoleQueryVo roleQueryVo) {
        Page<SysRole> rolePage = new Page<>(page, size);
        return baseMapper.selectPageByCondition(rolePage, roleQueryVo);
    }

    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
        //获取所有角色
        List<SysRole> roles = baseMapper.selectList(null);

        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        //获取用户已分配的角色
        List<SysUserRole> userRoles = userRoleMapper.selectList(queryWrapper);

        //获取用于已分配的角色id
        List<String> userRoleIds = userRoles.stream().map(SysUserRole::getRoleId)
                .map(String::valueOf).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", roles);
        map.put("userRoleIds", userRoleIds);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doAssign(AssginRoleVO assginRoleVo) {
        Long userId = assginRoleVo.getUserId();
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        //删除原来分配的角色
        userRoleMapper.delete(queryWrapper);

        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        List<SysUserRole> userRoles = new ArrayList<>();
        roleIdList.forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            userRoles.add(sysUserRole);
        });

        //批量保存
        return userRoleMapper.insert(userRoles);
    }
}
